package com.jinmingwu.musicplay.myApplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jinmingwu.musicplay.R;
import com.jinmingwu.musicplay.httpserver.LrcDownload;

import org.json.JSONException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class LrcActivity extends AppCompatActivity {

    private TextView tv_lrc;
    private LinearLayout linearLayout;

    private int status;

    // 广播接收器
    private StatusChangedReceiver receiver;

    private String lrc_data = null;
    private String filename = null;
    private String musicName = null;
    private String musicArtist = null;

    private AsyncDownLoad asyncDownLoad;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lrc);

        findView();
        bindStatusChangeReceiver();

        tv_lrc.setText(R.string.noPlaySong);

        // 检查状态
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        if (asyncDownLoad != null && !asyncDownLoad.isCancelled()) {
            asyncDownLoad.cancel(true);
        }
    }

    private void findView() {
        tv_lrc = (TextView) findViewById(R.id.lrc_tv_lrc);
        linearLayout = (LinearLayout) findViewById(R.id.lrc_linearlayout);
    }

    // 绑定广播接收器
    private void bindStatusChangeReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(
                MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS
        );
        registerReceiver(receiver, filter);
    }

    // 发送广播
    private void sendBroadcastOnCommand (int command) {
        Intent intent = new Intent(
                MusicService.BROADCAST_MUSICSERVICE_CONTROL
        );
        intent.putExtra("command", command);
        sendBroadcast(intent);
    }

    // 内部类，处理播放状态广播
    class StatusChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 获取播放器状态
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    musicName = intent.getStringExtra("musicName");
                    musicArtist = intent.getStringExtra("musicArtist");
                    LrcActivity.this.setTitle("正在播放：" + musicName + " " + musicArtist);
                    try {
                        get_lrc(LrcActivity.this);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    class AsyncDownLoad extends AsyncTask<String, Intent, String> {
        // 执行时调用该方法
        @Override
        protected String doInBackground(String... params) {
            String url = null;
            try {
                url = LrcDownload.getSongLRCUrl(params[0], params[1]);
                Log.i("TAG", url + "123");
                lrc_data = LrcDownload.getHtmlCode(url);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return lrc_data;
        }

        // 任务执行前执行该方法
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            tv_lrc.setText(R.string.lrcfinding);
        }

        // 任务结束时执行该方法
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result == null) {
                tv_lrc.setText(R.string.nolrc);
            } else {
                try {
                    FileOutputStream outputStream = LrcActivity.this.openFileOutput(filename, Context.MODE_PRIVATE);
                    outputStream.write(result.getBytes());
                    outputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String string = drawLrcWord(filename);
                tv_lrc.setText(string);
            }
        }
    }

    private void get_lrc(Context context) {
        String[] files = context.fileList();
        if (musicName != null) {
            filename = musicName + ".lrc";
            List<String> fileList = Arrays.asList(files);
            if (fileList.contains(filename)) {
                // 本地存在，则从本地读取
                Log.i("TAG", "has lrc file!");
                String string = drawLrcWord(filename);
                tv_lrc.setText(string);
            } else {
                // 本地不存在，则需从网络中下载
                // 检查网络状态
                ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = cwjManager.getActiveNetworkInfo();
                if (info != null && info.isAvailable()) {
                    Log.i("TAG", "has not lrc file!");
                    asyncDownLoad = new AsyncDownLoad();
                    asyncDownLoad.execute(LrcDownload.LRC_SEARCH_URL, musicName);
                } else {
                    Toast.makeText(getApplicationContext(), R.string.nonetwork, Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private String drawLrcWord(String filename) {
        String lrc_word = "";
        Pattern pattern = Pattern.compile("\\[\\d{2}:\\d{2}.\\d{2}\\]");
        File file = new File(getApplication().getFilesDir() + "/" + filename);
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line = "";
            while((line = reader.readLine()) != null) {
                Matcher m = pattern.matcher(line);
                line = m.replaceAll("");
                line = line.replace("[ti:", "");
                line = line.replace("[ar:", "");
                line = line.replace("[al:", "");
                line = line.replace("[by:", "");
                line = line.replace("[i:", "");
                line = line.replace("]", "");
                line = line.contains("offset")?"":line;
                line = line.replace("url", "歌词来源");
                line = line.replace("null", "");
                lrc_word += line + "/n";
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lrc_word;
    }





}
